package bt.basics.common.utils.fileUtils;


import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;


public class FileUtils {

    private final static Map<String, String> FILE_TYPE_MAP = new HashMap<>();

    static {
        getAllFileType();
    }

    /**
     * MultipartFile转为base64
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static String fileToBase64(MultipartFile file) throws Exception {
        String base64EncoderImg = "data:" + file.getContentType() + ";base64,";
        BASE64Encoder base64Encoder = new BASE64Encoder();
        byte[] imageByte = file.getBytes();
        byte[] newByte = ImageUtil.compressPicForScale(imageByte, 40);
        base64EncoderImg += base64Encoder.encode(imageByte);
        return base64EncoderImg;
    }

    /**
     * MultipartFile转为base64
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static String dnfileToBase64(MultipartFile file) throws Exception {
        BASE64Encoder base64Encoder = new BASE64Encoder();
        byte[] imageByte = file.getBytes();
        String base64EncoderImg = base64Encoder.encode(imageByte);
        return base64EncoderImg;
    }


    public static String fileToBase64(MultipartFile[] file) throws Exception {
        String base64EncoderImg = "";
        BASE64Encoder encoder = new BASE64Encoder();
        for (int i = 0; i < file.length; i++) {
            base64EncoderImg += "data:" + file[i].getContentType() + ";base64,";
            byte[] imageByte = file[i].getBytes();
            byte[] newByte = ImageUtil.compressPicForScale(imageByte, 40);
            base64EncoderImg += encoder.encode(newByte);
            if (i != file.length - 1) {
                base64EncoderImg += "|";
            }
        }
        return base64EncoderImg;
    }

    /**
     * 图片文件 ,分割
     * @param file
     * @return
     * @throws Exception
     */
    public static String fileToBase64Comma(MultipartFile[] file) throws Exception {
        String base64EncoderImg = "";
        BASE64Encoder encoder = new BASE64Encoder();
        for (int i = 0; i < file.length; i++) {
            base64EncoderImg += "data:" + file[i].getContentType() + ";base64,";
            byte[] imageByte = file[i].getBytes();
            byte[] newByte = ImageUtil.compressPicForScale(imageByte, 40);
            base64EncoderImg += encoder.encode(newByte);
            if (i != file.length - 1) {
                base64EncoderImg += ",";
            }
        }
        return base64EncoderImg;
    }

    /**
     * 网络图片转化为base64 | 分割
     *
     * @param imgURL 图片路径
     * @return 加密的base64码
     */
    public static String getImageStrFromUrl(String[] imgURL) {
        byte[] data = null;
        String str = "";
        InputStream inStream = null;
        BASE64Encoder encoder = new BASE64Encoder();
        try {
            for (int i = 0; i < imgURL.length; i++) {
                String imgbase64 = ImageUtil.getImageStrFromUrl(imgURL[i]);
                byte[] imageByte = new BASE64Decoder().decodeBuffer(imgbase64);
                byte[] newByte = ImageUtil.compressPicForScale(imageByte, 40);
                String newImgBase64 = "data:image/jpeg;base64," + encoder.encode(newByte);
                str += newImgBase64;
                if (i != imgURL.length - 1) {
                    str += "|";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != inStream)
                    inStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return str;
    }

    /**
     * 网络图片转化为base64 , 分割
     *
     * @param imgURL 图片路径
     * @return 加密的base64码
     */
    public static String getImageStrFromUrlComma(String[] imgURL) {
        byte[] data = null;
        String str = "";
        InputStream inStream = null;
        BASE64Encoder encoder = new BASE64Encoder();
        try {
            for (int i = 0; i < imgURL.length; i++) {
                String imgbase64 = ImageUtil.getImageStrFromUrl(imgURL[i]);
                byte[] imageByte = new BASE64Decoder().decodeBuffer(imgbase64);
                byte[] newByte = ImageUtil.compressPicForScale(imageByte, 40);
                String newImgBase64 = "data:image/jpeg;base64," + encoder.encode(newByte);
                str += newImgBase64;
                if (i != imgURL.length - 1) {
                    str += ",";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != inStream)
                    inStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return str;
    }

    /**
     * 网络文件转换成base64
     *
     * @param imgURL
     * @return
     */
    public static String getImageStrFromUrl(String imgURL) {
        byte[] data = null;
        String str = "";
        InputStream inStream = null;
        BASE64Encoder encoder = new BASE64Encoder();
        String name = "";
        try {
            String imgbase64 = ImageUtil.getImageStrFromUrl(imgURL);
            byte[] imageByte = new BASE64Decoder().decodeBuffer(imgbase64);
            InputStream inputStream = new ByteArrayInputStream(imageByte);
            name = getFileType(inputStream);
            String newImgBase64 = encoder.encode(imageByte);
            str = newImgBase64;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != inStream)
                    inStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return str + "," + name;
    }

    /**
     * 网络图片转化为base64
     *
     * @param imgURL 图片路径
     * @return 加密的base64码
     */
    public static String getPDFStrFromUrl(String imgURL) {
        byte[] data = null;
        String str = "";
        InputStream inStream = null;
        BASE64Encoder encoder = new BASE64Encoder();
        try {
            //for (int i = 0; i < imgURL.length; i++) {
            String imgbase64 = ImageUtil.getImageStrFromUrl(imgURL);
            byte[] imageByte = new BASE64Decoder().decodeBuffer(imgbase64);
            byte[] newByte = ImageUtil.compressPicForScale(imageByte, 40);
            String newPdfBase64 = "data:application/pdf;base64," + encoder.encode(newByte);
            str += newPdfBase64;
//                if (i != imgURL.length - 1) {
//                    str += ",";
//                }
            // }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != inStream)
                    inStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return str;
    }

    private static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }


    /**
     * 获取文件类型
     *
     * @param url
     * @return
     */
    public static String getFileType(String url) {
        InputStream is = null;
        try {
            is = new URL(url).openStream();
            byte[] bytes = new byte[10];
            if (is.read(bytes, 0, bytes.length) == -1)
                return null;
            String fileCode = bytesToHexString(bytes).toLowerCase();

            if (fileCode.length() > 1)
                for (String key : FILE_TYPE_MAP.keySet())
                    if (fileCode.startsWith(key.toLowerCase()) || key.toLowerCase().startsWith(fileCode))
                        return FILE_TYPE_MAP.get(key);
        } catch (Exception e) {
            return null;
        } finally {
            try {
                if (null != is)
                    is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 字节流获取文件头部
     *
     * @param inputStream
     * @return
     */
    public static String getFileType(InputStream inputStream) {
        InputStream is = inputStream;
        try {
            byte[] bytes = new byte[10];
            if (is.read(bytes, 0, bytes.length) == -1)
                return null;
            String fileCode = bytesToHexString(bytes).toLowerCase();

            if (fileCode.length() > 1)
                for (String key : FILE_TYPE_MAP.keySet())
                    if (fileCode.startsWith(key.toLowerCase()) || key.toLowerCase().startsWith(fileCode))
                        return FILE_TYPE_MAP.get(key);
        } catch (Exception e) {
            return null;
        }
        return null;
    }

    /**
     * 获取文件头
     *
     * @param src
     * @return
     */
    private static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (null == src || src.length < 1)
            return null;
        for (byte b : src) {
            int v = b & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2)
                stringBuilder.append(0);
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    /**
     * 文件头
     */
    private static void getAllFileType() {
        FILE_TYPE_MAP.put("ffd8ffe000104a464946", "jpg"); //JPEG (jpg)
        FILE_TYPE_MAP.put("89504e470d0a1a0a0000", "png"); //PNG (png)
        FILE_TYPE_MAP.put("47494638396126026f01", "gif"); //GIF (gif)
        FILE_TYPE_MAP.put("49492a00227105008037", "tif"); //TIFF (tif)
        FILE_TYPE_MAP.put("424d228c010000000000", "bmp"); //16色位图(bmp)
        FILE_TYPE_MAP.put("424d8240090000000000", "bmp"); //24位位图(bmp)
        FILE_TYPE_MAP.put("424d8e1b030000000000", "bmp"); //256色位图(bmp)
        FILE_TYPE_MAP.put("41433130313500000000", "dwg"); //CAD (dwg)
        FILE_TYPE_MAP.put("3c21444f435459504520", "html"); //HTML (html)
        FILE_TYPE_MAP.put("3c21646f637479706520", "htm"); //HTM (htm)
        FILE_TYPE_MAP.put("48544d4c207b0d0a0942", "css"); //css
        FILE_TYPE_MAP.put("696b2e71623d696b2e71", "js"); //js
        FILE_TYPE_MAP.put("7b5c727466315c616e73", "rtf"); //Rich Text Format (rtf)
        FILE_TYPE_MAP.put("38425053000100000000", "psd"); //Photoshop (psd)
        FILE_TYPE_MAP.put("46726f6d3a203d3f6762", "eml"); //Email [Outlook Express 6] (eml)
        FILE_TYPE_MAP.put("d0cf11e0a1b11ae10000", "doc"); //MS Excel 注意：word、msi 和 excel的文件头一样
        FILE_TYPE_MAP.put("d0cf11e0a1b11ae10000", "vsd"); //Visio 绘图
        FILE_TYPE_MAP.put("5374616E64617264204A", "mdb"); //MS Access (mdb)
        FILE_TYPE_MAP.put("252150532D41646F6265", "ps");
        FILE_TYPE_MAP.put("255044462d312e350d0a", "pdf"); //Adobe Acrobat (pdf)
        FILE_TYPE_MAP.put("2e524d46000000120001", "rmvb"); //rmvb/rm相同
        FILE_TYPE_MAP.put("464c5601050000000900", "flv"); //flv与f4v相同
        FILE_TYPE_MAP.put("00000020667479706d70", "mp4");
        FILE_TYPE_MAP.put("49443303000000002176", "mp3");
        FILE_TYPE_MAP.put("000001ba210001000180", "mpg"); //
        FILE_TYPE_MAP.put("3026b2758e66cf11a6d9", "wmv"); //wmv与asf相同
        FILE_TYPE_MAP.put("52494646e27807005741", "wav"); //Wave (wav)
        FILE_TYPE_MAP.put("52494646d07d60074156", "avi");
        FILE_TYPE_MAP.put("4d546864000000060001", "mid"); //MIDI (mid)
        FILE_TYPE_MAP.put("504b0304140000000800", "zip");
        FILE_TYPE_MAP.put("526172211a0700cf9073", "rar");
        FILE_TYPE_MAP.put("235468697320636f6e66", "ini");
        FILE_TYPE_MAP.put("504b03040a0000000000", "jar");
        FILE_TYPE_MAP.put("4d5a9000030000000400", "exe");//可执行文件
        FILE_TYPE_MAP.put("3c25402070616765206c", "jsp");//jsp文件
        FILE_TYPE_MAP.put("4d616e69666573742d56", "mf");//MF文件
        FILE_TYPE_MAP.put("3c3f786d6c2076657273", "xml");//xml文件
        FILE_TYPE_MAP.put("494e5345525420494e54", "sql");//xml文件
        FILE_TYPE_MAP.put("7061636b616765207765", "java");//java文件
        FILE_TYPE_MAP.put("406563686f206f66660d", "bat");//bat文件
        FILE_TYPE_MAP.put("1f8b0800000000000000", "gz");//gz文件
        FILE_TYPE_MAP.put("6c6f67346a2e726f6f74", "properties");//bat文件
        FILE_TYPE_MAP.put("cafebabe0000002e0041", "class");//bat文件
        FILE_TYPE_MAP.put("49545346030000006000", "chm");//bat文件
        FILE_TYPE_MAP.put("04000000010000001300", "mxp");//bat文件
        FILE_TYPE_MAP.put("504b0304140006000800", "docx");//docx文件
        FILE_TYPE_MAP.put("d0cf11e0a1b11ae10000", "wps");//WPS文字wps、表格et、演示dps都是一样的
        FILE_TYPE_MAP.put("6431303a637265617465", "torrent");


        FILE_TYPE_MAP.put("6D6F6F76", "mov"); //Quicktime (mov)
        FILE_TYPE_MAP.put("FF575043", "wpd"); //WordPerfect (wpd)
        FILE_TYPE_MAP.put("CFAD12FEC5FD746F", "dbx"); //Outlook Express (dbx)
        FILE_TYPE_MAP.put("2142444E", "pst"); //Outlook (pst)
        FILE_TYPE_MAP.put("AC9EBD8F", "qdf"); //Quicken (qdf)
        FILE_TYPE_MAP.put("E3828596", "pwl"); //Windows Password (pwl)
        FILE_TYPE_MAP.put("2E7261FD", "ram"); //Real Audio (ram)


        // images
        FILE_TYPE_MAP.put("FFD8FF", "jpg");
        FILE_TYPE_MAP.put("89504E47", "png");
        FILE_TYPE_MAP.put("47494638", "gif");
        FILE_TYPE_MAP.put("49492A00", "tif");
        FILE_TYPE_MAP.put("424D", "bmp");
        //
        FILE_TYPE_MAP.put("41433130", "dwg"); // CAD
        FILE_TYPE_MAP.put("38425053", "psd");
        FILE_TYPE_MAP.put("7B5C727466", "rtf"); // 日记本
        FILE_TYPE_MAP.put("3C3F786D6C", "xml");
        FILE_TYPE_MAP.put("68746D6C3E", "html");
        FILE_TYPE_MAP.put("44656C69766572792D646174653A", "eml"); // 邮件
        FILE_TYPE_MAP.put("D0CF11E0", "doc");
        FILE_TYPE_MAP.put("5374616E64617264204A", "mdb");
        FILE_TYPE_MAP.put("252150532D41646F6265", "ps");
        FILE_TYPE_MAP.put("255044462D312E", "pdf");
        FILE_TYPE_MAP.put("504B03040A00000000008", "docx");
        FILE_TYPE_MAP.put("504B0304", "zip");// zip 压缩文件
        FILE_TYPE_MAP.put("52617221", "rar");
        FILE_TYPE_MAP.put("57415645", "wav");
        FILE_TYPE_MAP.put("41564920", "avi");
        FILE_TYPE_MAP.put("2E524D46", "rm");
        FILE_TYPE_MAP.put("000001BA", "mpg");
        FILE_TYPE_MAP.put("000001B3", "mpg");
        FILE_TYPE_MAP.put("6D6F6F76", "mov");
        FILE_TYPE_MAP.put("3026B2758E66CF11", "asf");
        FILE_TYPE_MAP.put("4D546864", "mid");
        FILE_TYPE_MAP.put("1F8B08", "gz");
    }

    /**
     * base64解码
     *
     * @base64  base64码
     * @return 是否解密成功
     */
    public static byte[] base64ToByte(String base64) {
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] file = decoder.decodeBuffer(base64);
            return file;
        } catch (Exception e) {
            return null;
        }
    }


    public static void base64ToFile(String base64, String fileName) {
        File file = null;
        //创建文件目录
        String filePath="D:\\image";
        File  dir=new File(filePath);
        if (!dir.exists() && !dir.isDirectory()) {
            dir.mkdirs();
        }
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bytes = decoder.decodeBuffer(base64);
            file=new File(filePath+"\\"+fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}